// detail.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isSearch: true,
    isCear: false,
    val: '',
    isVisible: false,
    //定义数组用来储存获取的数据
    list: '',
    //定义数组用来存储每个选项卡中获取出来的数据
    detail: '',
    showTooltip: false,
    serviceTel:'',
    curID: 1,
    curIndex: 0,
    curSecondaryID: '',
    //定义变量用来储存首页传过来的id
    type: 0,
    secondaryList: [],
    secondaryLists: [{
      name: '全部'
    }],
    //定义变量用来储存每个门店选项卡的第一个选项的id
    indexID: 0,
    //监听输入框初始数据
    inputValue: 0,
    // 初始化隐藏样式
    hidden: true,
    //定义数组用来储存门店的背景图片和头像
    mendian: '',
    // weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    val: '',
    no_data: false
  },

  //
  getInput: function (e) {
    this.setData({
      val: e.detail.value
    })
    if (this.data.val.length > 0) {
      this.setData({
        isSearch: false,
        isCear: true,
      })
    } else {
      this.setData({
        isSearch: true,
        isCear: false,
      })
    }
  },
 
  switchSecondaryTab: function (e) {
    const id = e.currentTarget.dataset.id;
    console.log(id)
    const that = this
    wx.request({
      url: `https://199shq.com/api/categories/tp/${id}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token'),
      },
      success: function (res) {
        console.log(res.data.data);
        if (res.data.data.length == 0) {
          console.log("该分类暂时没有数据");
          that.setData({
            no_data: true
          })
        } else {
          that.setData({
            no_data: false
          })
        }
        var list = res.data.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            detail: res.data.data
          })
        }
      }
    })
    this.setData({
      curSecondaryID: id
    });
  },
  //
  cleartap: function () {
    this.setData({
      val: '',
      isSearch: true,
      isCear: false,
    })
  },
  toggleSubList: function (e) {
    let index = e.currentTarget.dataset.index;
    let activeIndex = this.data.activeIndex;
    if (activeIndex === index) {
        // 如果当前点击的是已展开的分类，关闭它
        this.setData({
            activeIndex: -1
        });
    } else {
        // 展开当前点击的分类，关闭其他展开的二级分类
        this.setData({
            activeIndex: index
        });
    }
},
  //点击控制购买商品的数量减少
  jian: function () {
    if (this.data.inputValue > 0) {
      this.setData({
        inputValue: this.data.inputValue - 1 // 将输入框的值赋给inputValue
      });
    }
    //判断当数量为0时则隐藏输入框
    if (this.data.inputValue < 1) {
      this.setData({
        hidden: true
      });
    }
  },

  //点击控制购买商品的数量增加
  create: function () {
    this.setData({
      inputValue: this.data.inputValue + 1 // 将输入框的值赋给inputValue
    });
    //判断当数量大于0是则显示输入框
    if (this.data.inputValue > 0) {
      this.setData({
        hidden: false
      });
    }
  },

  //用来绑定输入框里面的双向绑定
  handleInput: function (e) {
    this.setData({
      inputValue: e.detail.value // 将输入框的值赋给inputValue
    });
  },

  //事件处理函数
  switchRightTab: function (e) {
    // 获取item项的id，和数组下标值
    let id = e.target.dataset.id;
    let index = parseInt(e.target.dataset.index);
    var that = this;
    let list = this.data.list
    // let index = ids.currentTarget.dataset.index;
    let activeIndex = this.data.activeIndex;
    if (activeIndex === index) {
      // 如果当前点击的是已展开的分类，关闭它
      this.setData({
        activeIndex: -1
      });
    } else {
      // 展开当前点击的分类
      this.setData({
        activeIndex: index
      });
    }
    // console.log()
    let secondaryList = this.data.secondaryLists
    secondaryList[0].id = id;
    console.log(secondaryList)
    if (Array.isArray(list[index].children)) {
      // 使用concat方法合并数组

      this.setData({
        secondaryList: secondaryList.concat(list[index].children)
      });
      // console.log(this.data.secondaryList)
    } else {
      // 如果list[index].children不是数组，将其包装成数组再合并
      this.setData({
        secondaryList: secondaryList
      });
    }
    //把点击到某一项，设为当前index
    this.setData({
      curID: id,
      curIndex: index,
      curSecondaryID: id
      // secondaryList:list[index].children
    })
    wx.request({
      url: `https://199shq.com/api/categories/tp/${id}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token'),
      },
      success: function (res) {
        console.log(res.data.data);
        if (res.data.data.length == 0) {
          console.log("该分类暂时没有数据");
          that.setData({
            no_data: true
          })
        } else {
          that.setData({
            no_data: false
          })
        }
        var list = res.data.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            detail: res.data.data
          })
        }
      }
    })

  },
  switchRightTabs: function (ids) {
    // 获取item项的id，和数组下标值
    console.log(ids)
    let id = ids;
    // let index =  parseInt(e.target.dataset.index);
    var that = this;
    let list = this.data.list
    // console.log()
    let secondaryList = this.data.secondaryLists
    secondaryList[0].id = id;
    console.log(secondaryList)
    if (Array.isArray(list[0].children)) {
      // 使用concat方法合并数组

      this.setData({
        secondaryList: secondaryList.concat(list[0].children)
      });
      // console.log(this.data.secondaryList)
    } else {
      // 如果list[index].children不是数组，将其包装成数组再合并
      this.setData({
        secondaryList: secondaryList
      });
    }
    
    //把点击到某一项，设为当前index
    this.setData({
      curID: id,
      // curIndex: 0,
      curSecondaryID: id
      // secondaryList:list[index].children
    })
    wx.request({
      url: `https://199shq.com/api/categories/tp/${id}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token'),
      },
      success: function (res) {
        console.log(res.data.data);
        if (res.data.data.length == 0) {
          console.log("该分类暂时没有数据");
          that.setData({
            no_data: true
          })
        } else {
          that.setData({
            no_data: false
          })
        }
        var list = res.data.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            detail: res.data.data
          })
        }
      }
    })

  },
  // bindViewTap: function () {
  //   let that = this;
  //   let value = that.data.type;
  //   wx.navigateTo({
  //     url: '../category/category?value={{value}}'
  //   })
  // },

  //每次返回到首页时候都用进行一次缓存的清理
  removeStorageSync: function () {
    var app = getApp();
    var user_id = String(app.globalData.userInfo.wxUserId);
    // 清除缓存数据
    wx.removeStorageSync(user_id);
  },
  switchWeekDay(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      curWeekDay: index
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.removeStorageSync();
    let that = this;
    const now = new Date();
    const day = now.getDay();
    // JavaScript 中 getDay() 返回值 0 代表周日，这里转换为 7
    that.setData({
      curWeekDay: day === 0 ? 7 : day,
      activeIndex: 0,
    });
    // console.log("options" + options);
    that.setData({
      type: options.value
    });
    // 获取的options   address = JSON.parse(decodeURIComponent(options.address));
    const storeId = options.storeId;
    if (storeId) {
      that.setData({
        type: storeId
      });
    }
    let b = this.data.type; // 获取 b  
    this.setData({
      type: b
    });

    this.checkAndSetConfirmation(b);
    // const hasConfirmed = wx.getStorageSync('hasConfirmed');
    // if (hasConfirmed === '' || hasConfirmed === false) {
    //   // 获取后台弹窗内容  
    //   this.setData({
    //     isVisible: true,
    //   })
    //   this.fetchModalContent();
    // }
    this.getdata();
    this.getMendian();
this.toggleSubList();
  },
  checkAndSetConfirmation: function (b) {
    // 从本地存储获取 hasConfirmed  
    let storedIds = wx.getStorageSync('storedIds') || []; // 获取已存储的 IDs  
    console.log(b)
    if (storedIds.includes(b)) {
      // 如果存储中存在 b，则设置 hasConfirmed 为 true  
      // this.setData({ hasConfirmed: true });  
      this.setData({
        isVisible: false,
      })
    } else {
      // 如果存储中不存在 b，则设置为 false  
      // this.setData({ hasConfirmed: false });  
      let b = this.data.type; // 当前的 b  
      const that = this;
      wx.request({
        url: `https://199shq.com/api/warmTips/selectById?storeId=${b}`, // 替换为你的API接口  
        method: 'GET',
        success: function (res) {
          console.log(res.data.data)
          if (res.data.data !== undefined) {
            that.setData({
              title: res.data.data.title,
              content: res.data.data.content
            })
            that.setData({
              isVisible: true,
            })
          } else {
            console.log('进入')
            that.setData({
              isVisible: false,
            })
          }
        },
        fail: function (err) {
          if (res.data.data === undefined) {
            this.setData({
              isVisible: false,
            })
          }
          console.error('请求失败:', err);
        }
      });
    }
  },
  showTooltip: function (e) {
    // const list = this.data.list

    const tooltip = e.currentTarget.dataset.tooltip;
    console.log(tooltip)
    // console.log(list[])
    this.setData({
      showTooltip: true,
      tooltipContent: tooltip
    });
    // 一定时间后隐藏提示框
    setTimeout(() => {
      this.setData({
        showTooltip: false
      });
    }, 2000);
  },
  onConfirm: function () {
    let b = this.data.type; // 当前的 b  
    const that = this;
    let storedIds = wx.getStorageSync('storedIds') || []; // 获取已存储的 IDs  

    // 存储门店 ID  
    if (!storedIds.includes(b)) {
      storedIds.push(b);
      wx.setStorageSync('storedIds', storedIds);
    }

    this.setData({
      isVisible: false,
      hasConfirmed: true
    });

    // 获取内容  
    // this.fetchModalContent();  
  },
  //onload方法在页面加载完成时开始执行,并且加载数据库数据
  // 获取每个门店选项卡详情数据
  getdata: function () { //定义函数名称
    var that = this;
    let b = this.data.type;
    console.log(wx.getStorageSync('token'));
    wx.request({
      url: `https://199shq.com/api/stores/cate/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data);
        var list = res.data.data;
        let indexid = list[0].id;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            list: res.data.data,
            curID: res.data.data[0].id,
          })
          that.switchRightTabs(res.data.data[0].id)
          // this.setData({
          //   curID: id,
          //   curIndex: index
          // })
        }
        // wx.request({
        //   url: `https://199shq.com/api/categories/tp/${indexid}`,
        //   method: 'GET',
        //   header: {
        //     'Content-Type': 'application/json',
        //     'token': wx.getStorageSync('token')
        //   },
        //   success: function(res) {
        //     console.log(res.data.data);
        //     if (res.data.data.length == 0) {
        //       console.log("该分类暂时没有商品");
        //       that.setData({
        //         no_data: true
        //       })
        //     }else{
        //       that.setData({
        //         no_data: false
        //       })
        //     }
        //     var list = res.data.data;
        //     if (list == null) {
        //       var toastText = '数据获取失败';
        //       wx.showToast({
        //         title: 'toastText',
        //         icon: '',
        //         duration: 2000
        //       });
        //     } else {
        //       that.setData({
        //         detail: res.data.data
        //       })
        //     }
        //   }
        // })
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },

  //获取门店的背景图片和头像
  getMendian: function () { //定义函数名称
    var that = this;
    let b = this.data.type;
    console.log(b)
    wx.request({
      url: `https://199shq.com/api/stores/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data);
        var list = res.data.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            mendian: res.data.data,
            serviceTel:res.data.data.serviceTel
          })
        }
      }
    })
  },

  //搜索事件定义
  Search: function (event) {
    let b = this.data.type;
    console.log(b)
    const value = event.detail.value;
    console.log('输入内容：', value);
    //跳转到搜索页面，并且把值传递过去
    wx.navigateTo({
      url: `/pages/searchs/searchs?param1=${value}&storeId=${b}`
    })
  },

  //点击触发搜索
  onInput: function () {
    let b = this.data.type;
    console.log(b)
    const value = this.data.val;
    console.log('输入内容：', value);
    //跳转到搜索页面，并且把值传递过去
    wx.navigateTo({
      url: `/pages/searchs/searchs?param1=${value}&storeId=${b}`
    })
  },

  //点击获取input内容
  seldata: function (event) {
    const value = event.detail.value;
    console.log(value);
    this.setData({
      val: value,
      Search_del: true
    });
    if (value == '') {
      this.setData({
        Search_del: false
      });
    }
  },

  //点击清空搜索框
  Search_del: function () {
    this.setData({
      val: '',
      Search_del: false
    });
  },

  // // 获取第一个选项卡中的商品详情数据
  // getdetail: function () { //定义函数名称
  //   console.log(this.data.list);
  //   var that = this;
  //   wx.request({
  //     url: `http://localhost:8081/api/categories/28`,
  //     method: 'GET',
  //     header: {
  //       'content-type':'application/json'
  //     },
  //     success: function(res) {
  //       console.log(res.data);
  //       var list = res.data;
  //       if (list == null) {
  //         var toastText = '数据获取失败';
  //         wx.showToast({
  //           title: 'toastText',
  //           icon: '',
  //           duration: 2000
  //         });
  //       } else {
  //         that.setData({
  //           detail: res.data
  //         })
  //       }
  //     }
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})